package ws.performancetest.tests.jdbcdriver;

import java.sql.SQLException;
import java.util.concurrent.locks.ReentrantLock;
import ws.performancetest.api.annotation.PerformanceTest;
import ws.performancetest.api.exception.TestSuiteSetupException;
import ws.performancetest.tests.jdbcdriver.runnable.ResultSetRunnable;

/**
 *
 * @author Wilson Santos, <wilson.santos@ua.pt>
 */
public class MeasureDelayTest extends AbstractDriverTest {

  ReentrantLock lock = new ReentrantLock();

  public MeasureDelayTest() throws TestSuiteSetupException, SQLException {
    super("MeasureDelayTest_Results", "MeasureDelayTest_Summary");
  }

  @PerformanceTest(name = "Measure Delay")
  public void measureDelay() throws InterruptedException {
    ResultSetRunnable.setDelay(cycleCount);

    Thread[] tlist = new Thread[numberOfThreads];
    for (int i = 0; i < tlist.length; ++i) {
      tlist[i] = new Thread(new Runnable() {

        @Override
        public void run() {
          long t_start, t_finish;
          lock.lock();
          try {
            t_start = System.nanoTime();
            ResultSetRunnable.delayfunc();
            t_finish = System.nanoTime();
          } finally {
            lock.unlock();
          }
          addLog(t_finish - t_start);
        }
      });
    }
    for (int i = 0; i < tlist.length; ++i) {
      tlist[i].start();
    }
    for (int i = 0; i < tlist.length; ++i) {
      tlist[i].join();
    }
  }

  @PerformanceTest(name = "Print Delay")
  public void printDelay() throws InterruptedException {

    Thread[] tlist = new Thread[numberOfThreads];
    for (int i = 0; i < tlist.length; ++i) {
      tlist[i] = new Thread(new Runnable() {

        String s = "whatever!";

        @Override
        public void run() {
          long t_start, t_finish;
          t_start = System.nanoTime();
          System.out.print(s);
          System.out.print(s);
          System.out.print(s);
          System.out.print(s);
          System.out.print(s);
          System.out.print(s);
          System.out.print(s);
          System.out.print(s);
          t_finish = System.nanoTime();
          addLog(t_finish - t_start);
        }
      });
    }
    for (int i = 0; i < tlist.length; ++i) {
      tlist[i].start();
    }
    for (int i = 0; i < tlist.length; ++i) {
      tlist[i].join();
    }
  }
}
